<template>
  <Scroll
    ref="suggest"
    class="suggest"
    :data="result"
    :pullup="pullup"
    :pulldown="pulldown"
    :beforeScroll="beforeScroll"
    @scrollToEnd="searchMore"
    @scrollToStart="searchRefresh"
    @beforeScroll="listScroll"
  >
    <ul class="suggest-list">
      <li class="suggest-item" v-for="(item,index) in result" :key="index" v-show="!refresh" @click="selectItem(item)">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore" title></loading>
    </ul>
    <div v-show="!hasMore && !result.length" class="no-result-wrapper">
      <!-- <no-result title="抱歉，暂无搜索结果"></no-result> -->
    </div>
    <div class="no-result-wrapper" v-show="!result.length">
      <NoResult title="抱歉，暂无搜索结果"></NoResult>
    </div>
  </Scroll>
</template>

<script type="text/ecmascript-6">
import Scroll from '@/base/scroll/scroll'
import Loading from '@/base/loading/loading'
import NoResult from '@/base/no-result/no-result'
import { search, search2 } from '@/api/search'
import { ERR_OK } from '@/api/config'
import { createSong } from '@/assets/js/song'
import { mapMutations, mapActions } from 'vuex'
import Singer from '@/assets/js/singer'

const TYPE_SINGER = 'singer'
const perpage = 20

export default {
  props: {
    query: {
      type: String,
      default: ''
    },
    // 是否展示歌手
    showSinger: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      page: 1,
      result: [],
      hasMore: false,
      // 是否开启上拉加载
      pullup: true,
      total: 0,
      pulldown: true,
      refresh: false,
      // 滚动开始前的事件，收起小键盘，失去焦点
      beforeScroll: true
    }
  },
  methods: {
    fresh() {
      this.$refs.suggest.refresh()
    },
    async search() {
      // search(this.query, this.page, this.showSinger, 20).then((res) => {
      //   if ((res.code = ERR_OK)) {
      //     this.result = this._getResult(res.data)
      //   }
      // })
      // 第一次获取数据时，滚动到顶部
      this.$refs.suggest.scrollTo(0, 0)
      this.refresh = true
      this.page = 1
      this.hasMore = true
      let res = await search2(this.query, this.page, this.showSinger, perpage)
      console.log(res)
      if (res.data.result === 100) {
        let ret = []
        ret.push({ singername: res.data.data.key, type: TYPE_SINGER })
        ret = ret.concat(this._normalizeSongs(res.data.data.list))
        this.result = ret
        console.log(this.result)
        this._checkMore(res.data.data)
        this.refresh = false
      }
    },
    // 下拉刷新
    searchRefresh() {
      // this.page = 1
      // console.log('刷新')
      // this.refresh = true
      this.search()
    },
    _checkMore(data) {
      console.log(data)
      const song = data.list
      if (
        !song.length ||
        (data.pageNo - 1) * perpage + song.length >= data.total
      ) {
        console.log('222')
        this.hasMore = false
      }
    },
    _getResult(data) {
      let ret = []
      if (data.zhida && data.zhida.singerid) {
        ret.push({ ...data.zhida, ...{ type: TYPE_SINGER } })
      }
      if (data.song) {
        ret = ret.concat(data.song.list)
      }
      return ret
    },
    getIconCls(item) {
      if (item.type === TYPE_SINGER) {
        return 'icon-mine'
      } else {
        return 'icon-music'
      }
    },
    getDisplayName(item) {
      if (item.type === TYPE_SINGER) {
        return item.singername
      } else {
        return `${item.name}-${item.singer}`
      }
    },
    _normalizeSongs(list) {
      let ret = []
      list.forEach((musicData) => {
        if (musicData.songid && musicData.albummid) {
          ret.push(createSong(musicData))
        }
      })
      return ret
    },
    async searchMore() {
      if (!this.hasMore) {
        return
      }
      this.page++
      console.log(this.page)
      let res = await search2(this.query, this.page, this.showSinger, perpage)
      console.log(res)
      if (res.data.result === 100) {
        let ret = []
        ret = ret.concat(this._normalizeSongs(res.data.data.list))
        this.result = this.result.concat(ret)
        console.log(this.result)
        this._checkMore(res.data.data)
      }
    },
    // 点击事件
    selectItem(item) {
      console.log(item)
      if (item.type === TYPE_SINGER) {
        // const singer = new Singer({
        //   id: item.__ob__.dep.id,
        //   name: item.singername
        // })
        // this.$router.push({
        //   path: `/search/${singer.id}`
        // })
        // this.setSinger(singer)
        return
      }
      this.insertSong(item)
      this.$emit('select')
    },
    listScroll() {
      this.$emit('listScroll')
    },
    ...mapMutations({
      setSinger: 'SET_SINGER'
    }),
    ...mapActions(['insertSong'])
  },
  watch: {
    // 搜索词发生变化就去搜索
    query() {
      this.search()
    }
  },
  components: {
    Scroll,
    Loading,
    NoResult
  }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~@/assets/stylus/variable';
@import '~@/assets/stylus/mixin';

.suggest {
  height: 100%;
  overflow: hidden;

  .suggest-list {
    padding: 0 30px;

    .suggest-item {
      display: flex;
      align-items: center;
      padding-bottom: 20px;
    }

    .icon {
      flex: 0 0 30px;
      width: 30px;

      [class^='icon-'] {
        font-size: 14px;
        color: $color-text-d;
      }
    }

    .name {
      flex: 1;
      font-size: $font-size-medium;
      color: $color-text-d;
      overflow: hidden;

      .text {
        no-wrap();
      }
    }
  }

  .no-result-wrapper {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%);
  }
}
</style>